<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools :show-before="true">
        <template #before>共{{ page.total }}条记录</template>
        <template #after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcleFn"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click.native="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.staffPhoto"
                fit="contain"
                :preview-src-list="[row.staffPhoto]"
                :lazy="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column
            label="聘用形式"
            :formatter="formatterTypeFn"
            sortable
            prop="formOfEmployment"
          />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column
            :formatter="formatterDateFn"
            label="入职时间"
            sortable
            prop="timeOfEntry"
          />
          <el-table-column label="账户状态" sortable prop="enableState">
            <template #default="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" /> </template></el-table-column>
          <el-table-column label="操作" prop="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="handleAssignRole(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                @click.native="delFn(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件 -->
          <el-pagination
            :current-page="page.currentIndex"
            :page-sizes="page.pagesizes"
            :page-size="page.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployee :show-dialog.sync="showDialog" @reload="getEmployeeListFn" />
    <AssignRole
      :show-role-dialog.sync="role.showRoleDialog"
      :user-id="role.userId"
    />
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeeAPI } from '@/api/employees.js'
import EmployeeEnum from '@/model/employees.js'
import { formatDate } from '@/filters/index.js'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'

export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      employeeList: [], // 数据列表
      page: {
        currentIndex: 1, // 当前页码
        pagesize: 8, // 默认页容量
        pagesizes: [2, 4, 6, 8], // 页容量范围
        total: 200 // 总条数
      }, // 分页数据
      showDialog: false,
      role: {
        showRoleDialog: false,
        userId: ''
      } // 角色管理数据
    }
  },
  watch: {
    // 分页数据有任何变化都重新获取列表
    page: {
      deep: true,
      handler() {
        this.getEmployeeListFn()
      }
    }
  },
  created() {
    this.getEmployeeListFn()
  },
  methods: {
    // 选择角色
    handleAssignRole(id) {
      this.role = { showRoleDialog: true, userId: id }
    },
    // 获取数据列表
    async getEmployeeListFn() {
      const { pagesize, currentIndex } = this.page
      const res = await getEmployeeListAPI({
        page: currentIndex,
        size: pagesize
      })
      const { total, rows } = res
      this.employeeList = rows // 列表数据
      this.page.total = total // 总条数
      if (this.page.pagesizes.indexOf(total) === -1) {
        this.page.pagesizes.push(total) // 把总条数加入页容量可选项
      }
    },
    // 页容量改变
    handleSizeChange(val) {
      this.page.pagesize = val
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page.currentIndex = val
    },
    // 格式化时间
    formatterDateFn(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      return formatDate(cellValue)
    },
    // 格式化聘用形式
    formatterTypeFn(row, column, cellValue, index) {
      const res = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return res ? res.value : '未知'
    },
    /* //* 格式化在职状态
    formatterStateFn(row, column, cellValue, index) {
      const res = EmployeeEnum.workingState.find(item => item.id == cellValue)
      return res ? res.value : '未知'
    } */
    // 删除员工
    delFn(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message.success('删除成功!')
          delEmployeeAPI(id)
          this.page.currentIndex = 1 // 重置页码并刷新数据
        })
        .catch(() => this.$message.info('取消删除'))
    },
    // 导出excle
    async exportExcleFn() {
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      const { rows } = await getEmployeeListAPI({
        page: 1,
        size: this.page.total
      })
      // console.log(rows)
      // 获取表头
      let header = Object.keys(rows[0])
      // console.log(header)
      // 获取数据
      const data = this.formatData(rows, header)
      // 表头改成中文
      header = header.map(key_en => this.en2zh(key_en))
      export_json_to_excel({ header, data })
    },
    // 转中文
    en2zh(str) {
      // 字典
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        密码: 'password',
        头像: 'staffPhoto'
      }
      let key = str
      // 转中文
      Object.keys(dict).map(key_zh => {
        if (str === dict[key_zh]) key = key_zh
      })
      return key
    },
    // 转二维数组
    formatData(list, header) {
      const data = []
      list.map(item => {
        const arr = []
        header.map(head => {
          const index = header.indexOf(head)
          // 格式化聘用形式
          if (head === 'formOfEmployment') {
            return (arr[index] = this.formatterTypeFn(null, null, item[head]))
          }
          // 格式化时间
          if (head.indexOf('ime') !== -1) {
            return (arr[index] = formatDate(item[head]))
          }
          // 其他数据直接返回
          arr[index] = item[head]
        })
        data.push(arr)
      })
      return data
    }
  }
}
</script>
